/**********************************************************************************************
 * Copyright 2009 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file 
 * except in compliance with the License. A copy of the License is located at
 *
 *       http://aws.amazon.com/apache2.0/
 *
 * or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under the License. 
 *
 * ********************************************************************************************
 *
 *  Amazon Product Advertising API
 *  Signed Requests Sample Code
 *
 *  API Version: 2009-03-31
 *
 */

package webservice.amazon;

import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/*
 * This class shows how to make a simple authenticated ItemLookup call to the
 * Amazon Product Advertising API.
 * 
 * See the README.html that came with this sample for instructions on
 * configuring and running the sample.
 */
public class ItemSearch {
	private SignedRequestsHelper helper;
	private String requestUrl;
	private Map<String, String> result; 
	
	
    public ItemSearch() {
        /*
         * Set up the signed requests helper 
         */
        try {
            this.helper = SignedRequestsHelper.getInstance(Constants.ENDPOINT, Constants.AWS_ACCESS_KEY_ID, Constants.AWS_SECRET_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        

    }

    /*
     * Utility function to fetch the response from the service and extract the
     * title from the XML.
     */
    public Map<String, String> getResponse(String keyword) {
		this.createRequestURL(keyword);
       this.result = new HashMap<String, String>();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(this.requestUrl);
//            Node titleNode = doc.getElementsByTagName("Title").item(0);
//			this.result.put("Title", titleNode.getTextContent());
			XPath xPath = XPathFactory.newInstance().newXPath();
			this.result.put("Title", xPath.evaluate(Constants.NAME_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("DetailPageURL", xPath.evaluate(Constants.DETAIL_PAGE_URL_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("ASIN", xPath.evaluate(Constants.ASIN_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("LargeImage", xPath.evaluate(Constants.LARGEIMAGE_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("Binding", xPath.evaluate(Constants.BINDING_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("Brand", xPath.evaluate(Constants.BRAND_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("IsAdultProduct", xPath.evaluate(Constants.ISADULTPRODUCT_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("PriceAmount", xPath.evaluate(Constants.PRICE_AMOUNT_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("PriceCurrency", xPath.evaluate(Constants.PRICE_CURRENCY_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("Platform", xPath.evaluate(Constants.PLATFORM_PATH, doc, XPathConstants.STRING).toString());
			this.result.put("ReleaseDate", xPath.evaluate(Constants.RELEASEDATE_PATH, doc, XPathConstants.STRING).toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return this.result;
    }
	
	private void createRequestURL(String keyword) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("Service", "AWSECommerceService");
        params.put("ResponseGroup", "Large");		
		params.put("AssociateTag", Constants.ASSOCIATE_TAG);
        params.put("Operation", "ItemSearch");
        params.put("MerchantId", "All");
		params.put("SearchIndex", "All");
		params.put("Keywords", keyword);

        this.requestUrl = this.helper.sign(params);
		
	}

}
